<template>
  <div class="contianer">

    <div class="sendCount">
      <el-popover placement="top" width="500" trigger="click" class="popover">
        <div class="imgUpload">
          <el-upload class="upload-demo" ref="upload" action="api/util/uploadImg" name="imgFile"
            :before-upload="beforeUpload" :on-success="onSuccess" :on-preview="handlePreview"
            :before-remove="handleRemove" :file-list="fileList" :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取图片</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">发送</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10M</div>
          </el-upload>
        </div>
        <el-button slot="reference" style="background-color:rgb(104, 181, 244);">图片</el-button>

      </el-popover>

      <el-popover placement="top" width="500" trigger="click" class="popover">
        <div class="imgUpload">
          <el-upload class="upload-demo" ref="uploadFile" action="api/util/uploadFile" name="uploadFile"
            :before-upload="fileBeforeUpload" :on-success="onSuccessFile" :on-preview="handlePreview"
            :before-remove="handleRemoveFile" :file-list="fileList" :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUploadFile">发送</el-button>
            <div slot="tip" class="el-upload__tip">上传的格式全转化为文件，大小不能超过1G</div>
          </el-upload>
        </div>
        <el-button slot="reference" style="background-color:rgb(254, 206, 74);">文件</el-button>
      </el-popover>

      <el-input v-model="MyCommentSend.content" placeholder="请输入内容..." class="sendInput"
        @keyup.enter.native="sendInput"></el-input>
      <el-button type="primary" @click="sendInput">发送</el-button>


    </div>
    <div class="mess" ref="mess">
      <el-backtop target=".mess" :visibility-height="100"></el-backtop>
      <!-- 使用列表，建评论表 -->

      <!-- 菜单弹出框 -->
      <vue-context-menu :contextMenuData="contextMenuData" @delete="deleteComment"></vue-context-menu>
      <vue-context-menu :contextMenuData="userMenuData" @callOne="callOne"></vue-context-menu>
      <!--  -->

      <table class="messTable" v-for="(item, index) in communitys" :key="item.id + '' + index">
        <tr>
          <div v-if="isCommunitysCreatedTime(index, communitys)" style="text-align: center;margin-top: 30px;">
            <span class="text" style="border-radius: 1px;padding-left:3px;padding-right: 3px;">{{
              communitysCreatedTime(communitys[index]) }}</span>
          </div>
        </tr>
        <tr>
          <td>
            <div class="commentMess">
              <!-- 头像 -->
              <div @contextmenu="userMenu(item.uid)" @mousedown="lookUserMenu(item.uid, $event)"
                :class="item.uid == MyCommentSend.uid ? 'commontImg rigthText' : 'commontImg leftText'">
                <el-image :src="item.avatar ? item.avatar : circleUrl" style="pointer-events: none;"></el-image>
              </div>
              <!-- 文本 -->
              <div v-if="item.type == 0" @contextmenu="showMenu(item.id, item.uid)"
                :class="item.uid == MyCommentSend.uid ? 'commontText rigthText' : 'commontText leftText'">
                <span class="text">{{ item.content }}</span>
              </div>
              <!-- 图片 -->
              <div @contextmenu="showMenu(item.id, item.uid)" v-if="item.type == 1"
                :class="item.uid == MyCommentSend.uid ? 'rigthImg' : ' leftImg'"
                style=" width: 100px;object-fit: contain;">
                <el-image style="object-fit: contain;" :src="item.content" :preview-src-list="[item.content]">
                </el-image>
              </div>
              <!-- 文件 -->
              <div @contextmenu="showMenu(item.id, item.uid)" v-if="item.type == 2"
                :class="item.uid == MyCommentSend.uid ? ' rigthText' : ' leftText'">
                <!-- <span class="text">{{ item.fileName }}</span> -->
                <el-button style="background-color: rgb(239, 182, 132);width: 170px;" @click="uploadFile(item.content)">
                  <p class="el-icon-folder-opened"></p>:{{ fileName(item.fileName) }}
                </el-button>
              </div>
              <!-- 撤回消息 -->
              <div v-if="item.type == -1" style="text-align: center;">
                <span class="text"
                  style="background-color: #cccccc;border-radius: 1px;padding-left:3px;padding-right: 3px;">该消息已撤回</span>
              </div>
              <!-- 管理员撤回 -->
              <div v-if="item.type == -2" style="text-align: center;">
                <span class="text"
                  style="background-color: #cccccc;border-radius: 1px;padding-left:3px;padding-right: 3px;">该消息存在违规信息，已被管理员撤回</span>
              </div>
            </div>
          </td>
          <td style="width: 40%;">
            <div class="communitysInformation">
              <el-table height="470" :default-sort="{ prop: 'speakNum', order: 'descending' }"
                :data="allUserList.filter(data => !search || data.nickName.toLowerCase().includes(search.toLowerCase()))"
                style="width: 100%">
                <el-table-column prop="date" width="40">
                  <template slot-scope="scope">
                    <el-image :src="scope.row.avatar" class=" tableImg" v-if="scope.row.avatar"></el-image>
                    <div class="tableNoImg el-icon-picture-outline " v-else>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="社区用户列表" prop="nickName">
                </el-table-column>
                <el-table-column label="活跃度" prop="speakNum" width="100" sortable>
                </el-table-column>
                <el-table-column align="right" width="150">
                  <template slot="header" slot-scope="scope">
                    <el-input v-model="search" size="mini" placeholder="输入关键字搜索" />
                  </template>
                  <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row)" v-if="!scope.row.ban"
                      type="danger" plain>禁言</el-button>
                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row)" v-else
                      type="danger">解除</el-button>
                    <el-button size="mini" type="info" @click="handleDelete(scope.$index, scope.row)"
                      disabled>踢出</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!-- <table v-for="(item, index) in allUserList" :key="item.id + '' + index">
                <tr>
                  <div class="commontImg left">
                    <el-image :src="item.avatar ? item.avatar : circleUrl" style="pointer-events: none;"></el-image>
                  </div>
                  <div class="left">
                    {{ item.nickName }}
                  </div>
                </tr>

              </table> -->

            </div>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
  
<script>

export default {

  name: 'App',
  data() {
    return {
      search: '',
      allUserList: [],//所有用户的列表
      circleUrl: "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
      contextMenuData: {

        menuName: "demo",
        axis: {
          x: null,
          y: null
        },
        // Menu options (菜单选项)
        menulists: [
          {
            fnHandler: "delete", // Binding events(绑定事件)
            // icoName: "el-icon-delete-solid", // icon (icon图标 )
            btnName: "撤回" // The name of the menu option (菜单名称)
          },
        ]
      },
      userMenuData: {
        menuName: "@user",
        axis: {
          x: null,
          y: null
        },
        menulists: [
          {
            fnHandler: "callOne", // Binding events(绑定事件)
            icoName: "fa fa-home fa-fw", // icon (icon图标 )
            btnName: "@"// The name of the menu option (菜单名称)
          },
        ]
      },
      fileList: [

      ],
      communitys: [

      ],
      content: "",
      MyCommentSend: {
        uid: JSON.parse(sessionStorage.getItem("userMess")).id,
        content: '',
        type: '',
        avatar: JSON.parse(sessionStorage.getItem("userMess")).avatar,
        fileName: '',
      },
      isFileTypeError: false,//是否是人为删除已经删上传的文件
      nowScrollHeight: 0,//当前信息框的信息总长度，用来判断是否要将下拉条重置到最下面
      commentOperateId: '',
      lookOneUserMess: {
        nickName: '@',
      },
      visible: false,
    }
  },
  created() {
    this.AutomaticUpdate();
    this.init();
  },
  mounted() {
    //页面挂载完成时调用
    // this.scrollToBottom()
  },
  updated() {
    //页面更新后调用
    this.scrollToBottom()
  },
  methods: {
    handleEdit(index, row) {
      console.log(row);
      if (row.ban) {
        this.$confirm('是否解除昵称为\'' + row.nickName + '\'用户的禁言?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios.get("api/admin/wqunCommunityBan/deleteBan?id=" + row.id).then((res) => {
            this.$message({
              type: res.data.success ? 'success' : 'error',
              message: res.data.message,
            })
            if (res.data.success) {
              this.getCommunityUserMess();
            }
          })
        }).catch(() => { });
      } else {
        this.$confirm('是否禁言昵称为\'' + row.nickName + '\'的用户?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios.get("api/admin/wqunCommunityBan/addBan?id=" + row.id).then((res) => {
            this.$message({
              type: res.data.success ? 'success' : 'error',
              message: res.data.message,
            })
            if (res.data.success) {
              this.getCommunityUserMess();
            }
          })
        }).catch(() => { });
      }


    },
    handleDelete(index, row) {
      console.log(index, row);
    },
    communitysCreatedTime(index) {
      return index.createdTime;
    },
    isCommunitysCreatedTime(index, communitys) {
      if (index == 0) {
        return true;
      } else {
        var thisTime = communitys[index].createdTime;
        var preTime = communitys[index - 1].createdTime;
        let thisDate = new Date(thisTime);
        let preTDate = new Date(preTime);
        const diff = thisDate.getTime() - preTDate.getTime();
        if (diff / (1000 * 60 * 30) >= 1) {
          return true;
        } else {
          false
        }
      }
    },
    fileName(name) {
      if (name.length > 10) {
        var end = name.lastIndexOf('.')
        var fileName = name.substr(0, 5);
        var typeName = name.substr(end);
        name = fileName + "..." + typeName;
      }

      return name
    },
    deleteComment() {
      this.$axios.get("api/admin/wqunCommunity/adminDeleteCommunityById?id=" + this.commentOperateId).then((res) => {
        this.$message({
          type: res.data.success ? 'success' : 'error',
          message: res.data.message,
        })
        if (res.data.success) {
          this.getAllCommunity();
        }
      })
    },
    showMenu(id, uid) {
      this.commentOperateId = id;
      event.preventDefault();
      var x = event.clientX;
      var y = event.clientY;
      // Get the current location
      this.contextMenuData.axis = {
        x,
        y
      };
    },
    callOne() {
      this.MyCommentSend.content = "@" + this.lookOneUserMess.nickName;
    },

    lookUserMenu(uid, event) {
      if (event.button == 0) {
        // this.$axios.get("api/wqunAccountController/findAccountPublicById/" + uid).then((res) => {
        //   if (res.data.success) {
        //     this.lookOneUserMess = res.data.data.findAccountPublicById;
        //   }
        // })
        sessionStorage.setItem("lookUserMessById", uid);
        this.$router.push({
          name: 'publicBaseMess',
        })
      }

    },
    userMenu(uid) {
      this.$axios.get("api/wqunAccountController/findAccountPublicById?uid=" + uid).then((res) => {
        if (res.data.success) {
          this.lookOneUserMess = res.data.data.findAccountPublicById;
        }
      })
      event.preventDefault();
      var x = event.clientX - 10;
      var y = event.clientY;
      // Get the current location
      this.userMenuData.axis = {
        x,
        y
      };
    },
    test(id, event) {
      if (event.button == 0) {
        alert("你点了左键" + id);
      } else if (event.button == 2) {
        alert("你点了右键" + id);
      }
    },
    uploadFile(url) {
      window.location.href = url
    },
    beforeUpload(file) {
      if (file.type != "image/jpeg" && file != "image/png") {
        this.$message({
          type: "warning",
          message: '文件格式有误，请发送jpg或png格式的图片'
        })
        this.isFileTypeError = true;
        return false;
      };
    },
    submitUpload() {
      this.$refs.upload.submit();
    },

    submitUploadFile() {
      this.$refs.uploadFile.submit();
    },
    handleRemove(file, fileList) {
      if (!this.isFileTypeError) {
      } else {
        this.isFileTypeError = false;
      }

    },

    handleRemoveFile(file, fileList) {
      if (!this.isFileTypeError) {
      } else {
        this.isFileTypeError = false;
      }

    },
    onSuccessFile(response, file, fileList) {
      if (response.success) {
        this.MyCommentSend.type = 2;
        this.MyCommentSend.content = response.data.resPath;
        this.$axios.post("api/admin/wqunCommunity/addCommunity", this.MyCommentSend).then((res) => {
          if (res.data.success) {
            this.getAllCommunity();
            this.MyCommentSend.content = "";
            this.fileList = [];
          }
        })
      } else {
        this.$message({
          type: 'error',
          message: response.message,
        })
        return false;
      }
    },
    fileBeforeUpload(file) {

      console.log(file);
      this.MyCommentSend.fileName = file.name;
    },
    onSuccess(response, file, fileList) {
      if (response.success) {
        this.MyCommentSend.type = 1;
        this.MyCommentSend.content = response.data.resPath;
        this.$axios.post("api/admin/wqunCommunity/addCommunity", this.MyCommentSend).then((res) => {

          if (res.data.success) {
            this.getAllCommunity();
            this.MyCommentSend.content = "";
            this.fileList = [];
          }
        })
      } else {
        this.$message({
          type: 'error',
          message: response.message,
        })
        return false;
      }

    },
    handlePreview(file) {
    },
    scrollToBottom() {
      // 聊天定位到底部
      let mess = this.$refs.mess;    //通过$refs获取到该元素
      if (this.nowScrollHeight === mess.scrollHeight) {
        return;
      }

      else if (mess.scrollTop <= mess.scrollHeight - 1000 && this.nowScrollHeight != 0) {
        return;
      }
      mess.scrollTop = mess.scrollHeight;
      this.nowScrollHeight = mess.scrollHeight;
    },
    init() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgb(0, 0, 0, 0.8)'
      });
      setTimeout(() => {
        loading.close();
      }, 2000);
      this.getAllCommunity();
      this.getCommunityUserMess();

    },

    //社区讨论信息
    getAllCommunity() {
      this.$axios.get("api/admin/wqunCommunity/findAllCommunityFirst").then((res) => {
        if (res.data.success) {
          this.communitys = res.data.data.findAllCommunity;
        } else {
          this.$message({
            type: 'error',
            message: '请检查网络',
          })
        }
      })
    },

    //更新社区用户列表
    getCommunityUserMess() {
      this.$axios.get("api/admin/wqunCommunity/admin/communityUserMess", {
        headers: {
          'token': "123123123",
        }
      }).then((res) => {
        if (res.data.success) {
          this.allUserList = res.data.data.communityUserMess;
        } else {
          this.$message({
            type: 'error',
            message: '网咯异常'
          })
        }
      })
    },
    AutomaticUpdate() {
      setInterval(() => {
        setTimeout(() => {
          this.$axios.get("api/admin/wqunCommunity/findAllCommunity").then((res) => {
            if (res.data.success) {
              this.communitys = res.data.data.findAllCommunity;
            } else {
              this.$message({
                type: 'error',
                message: '请检查网络',
              })
            }
          })
        }, 0)
      }, 7000)
      setInterval(() => {
        setTimeout(() => {
          this.getCommunityUserMess();
        }, 0)
      }, 1000 * 60)//每分钟请求一次用户数据
    },
    sendInput() {
      if (this.MyCommentSend.content == "") {
        this.$message({
          type: 'warning',
          message: "输入内容不能为空"
        });
        return;
      }

      this.MyCommentSend.type = 0;
      this.$axios.post("api/admin/wqunCommunity/addCommunity", this.MyCommentSend).then((res) => {
        if (res.data.success) {
          this.getAllCommunity();
        }
      })
      this.MyCommentSend.content = "";
    },

  }
}
</script>
  
<style scoped>
.communitysInformation {
  width: 30%;
  height: 65%;
  position: fixed;
  background-color: #ffffff;
  top: 100px;
  left: 64%;
  border-radius: 10px;
  border: solid 10px #cccccc;
  overflow-y: scroll;
  padding: 20px;
}

.left {
  float: left;
}

.popover {
  margin-left: 3px;
}

.leftImg {
  float: left;
}

.rigthImg {
  float: right;
}


.imgUpload {
  border: solid 1px #cccccc;
  padding: 5px;
}

.upload-demo {
  margin: 0 auto;
  margin-left: 150px;
}



.contianer {
  height: 95%;
  min-height: 400px;


}

.sendCount {
  width: 100%;
  height: 40px;
  line-height: 30px;
  position: fixed;
  bottom: 30px;
}

.mess {
  height: 95%;
  overflow-y: auto;
  border-bottom: solid 1px #cccccc;
  padding: 10px;
  min-width: 500px;
}

.commentMess {
  margin-top: 15px;
}

.leftText {
  float: left;
  background-color: #bce9ea;
}

.rigthText {
  float: right;
  background-color: #47dfe1;
}

.commontText {
  max-width: 60%;
  min-height: 20px;
  border-radius: 10px;
  padding: 10px;

  .text {
    line-height: 20px;
    top: 8px;
    margin-left: 10px;
    margin-right: 10px;
  }

}

.messTable {
  position: relative;
  min-width: 100%;
}


.commontImg {
  height: 40px;
  width: 40px;
  margin-left: 5px;
  margin-right: 5px;
}

tr {}


.sendInput {
  width: 40%;
  margin-right: 10px;
}

div::-webkit-scrollbar {
  width: 6px;
}

div::-webkit-scrollbar-track {
  background: rgb(239, 239, 239);
  border-radius: 2px;
}

div::-webkit-scrollbar-thumb {
  background: #47dfe1;
  border-radius: 10px;
}

div::-webkit-scrollbar-thumb:hover {
  background: #47dfe1;
}
</style>